import { saveFile, saveOrUpdateBrand, getSupplierBrandInfo } from '../../../../api/index'
const uploadOss = require('../../../../utils/upload/uploadImg.js')
import { uuid } from '../../../../utils/util'

Page({
  data: {
    certificateFileList: [],
    logoFiles: [],
    form: {
      name: '',
      logoId: '',
      isImport: '',
      trademarkRegistrationNumber: '',
      brandCompany: '',
      isImportName: '',
      logoFiles: {},
      certificateFileList: []
    },
    isImports: [
      { label: '进口', value: 1 },
      { label: '国产', value: 2 }
    ]
  },
  async submit () {
    try {
      if (!this.data.form.name) {
        wx.showToast({ title: '请输入品牌名称！', icon: 'none' })
        return
      }
      if (!this.data.form.trademarkRegistrationNumber) {
        wx.showToast({ title: '请输入商标注册号！', icon: 'none' })
        return
      }
      if (!this.data.form.brandCompany) {
        wx.showToast({ title: '请输入品牌公司！', icon: 'none' })
        return
      }
      if (!this.data.form.isImport) {
        wx.showToast({ title: '请选择产地！', icon: 'none' })
        return
      }
      if (!this.data.form.logoUrl) {
        wx.showToast({ title: '请上传logo图片！', icon: 'none' })
        return
      }
      if (!this.data.form.certificateFileList.length) {
        wx.showToast({ title: '请上传证书图片！', icon: 'none' })
        return
      }
      wx.showLoading({ title: '保存中...', mask: true })
      await saveOrUpdateBrand({ ...this.data.form })
      wx.hideLoading()
      wx.$nav.navigateBack()
    } catch (err) {
      wx.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  changeInput ({ currentTarget: { dataset: { key } }, detail }) {
    this.setData({ ['form.' + key]: detail.value })
  },
  changeArea ({ detail: { value } }) {
    this.setData({ 'form.isImport': this.data.isImports[value].value, 'form.isImportName': this.data.isImports[value].label })
  },
  deleteTempFile ({ currentTarget: { dataset: { key, index } } }) {
    this.data[key].splice(index, 1)
    this.setData({ [key]: this.data[key] })
  },
  deleteFile ({ currentTarget: { dataset: { key, index } } }) {
    if (key === 'logoFiles') {
      this.setData({ 'form.logoFiles': {}, 'form.logoUrl': '' })
    } else {
      this.data.form[key].splice(index, 1)
      this.setData({ ['form.' + key]: this.data.form[key] })
    }
  },
  async againUpload ({ target: { dataset: { key, item, index } } }) {
    let _this = this
    let tempFiles = this.data[key]
    tempFiles[index].success = ''
    _this.setData({
      [key]: tempFiles
    })
    const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
    if (file) {
      const { ResultSet } = await saveFile({
        fileList: [{
          fileSize: item.size,
          fileName: file.fileName,
          fileUrl: file.fileUrl
        }]
      })
      tempFiles.splice(index, 1)
      _this.data.form[key] = {
        uuid: item.uuid,
        fileId: ResultSet.userData.fileIdList[0].fileId,
        fileName: file.fileName,
        fileUrl: ResultSet.userData.fileIdList[0].fileUrl,
        url: ResultSet.userData.fileIdList[0].url
      }
    } else {
      tempFiles[index].success = 1
      _this.setData({
        fileList: tempFiles
      })
    }
    _this.setData({
      [key]: tempFiles,
      ['form.' + key]:  _this.data.form[key]
    })
    if (key === 'logoFiles') {
      _this.setData({ 'form.logoId': _this.data.form.logoFiles.fileId })
    }
  },
  addFile ({ target: { dataset: { key, num } } }) {
    let _this = this
    let count = parseInt(num)
    if (key === 'certificateFileList') {
      count = parseInt(num) - _this.data.form[key].length
    }
    if (count <= 0) {
      wx.showToast({ title: `该图片最多只能上传${num}张`, icon: 'none' })
      return
    }
    wx.chooseMedia({
      count: count,
      mediaType: ['image'],
      async success (res) {
        _this.setData({ [`currentDiyItem.${key}`]: {} })
        res.tempFiles.forEach(item => {
          item.uuid = uuid()
          item.progress = 0
        })
        _this.data[`${key}`].push(...res.tempFiles)
        _this.setData({
          [`${key}`]: _this.data[`${key}`]
        })
        let tempFiles = _this.data[`${key}`]
        let temFileList = []
        if (tempFiles.length) {
          temFileList = await Promise.all(tempFiles.map(async (item, index) => {
            const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
            if (file) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileSize: item.size,
                  fileName: file.fileName,
                  fileUrl: file.fileUrl
                }]
              })
              return {
                uuid: item.uuid,
                fileId: ResultSet.userData.fileIdList[0].fileId,
                fileName: file.fileName,
                fileUrl: ResultSet.userData.fileIdList[0].fileUrl,
                url: ResultSet.userData.fileIdList[0].url
              }
            } else {
              tempFiles[index].success = 1
              _this.setData({
                [`${key}`]: tempFiles
              })
            }
          }))
        }
        let tempFileList = temFileList.filter(item => item)
        if (key === 'logoFiles') {
          _this.data.form[key] = tempFileList[0]
          if (_this.data.form[key] && _this.data.form[key].uuid) {
            let rowIndex = tempFiles.findIndex(row => _this.data.form[key].uuid === row.uuid)
            if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
          }
        } else {
          _this.data.form[key].push(...tempFileList)
          _this.data.form[key].forEach((item) => {
            let rowIndex = tempFiles.findIndex(row => row.uuid === item.uuid)
            if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
          })
        }
        _this.setData({
          [`${key}`]: tempFiles,
          [`form.${key}`]: _this.data.form[key]
        })
        if (key === 'logoFiles') {
          _this.setData({ 'form.logoId': _this.data.form.logoFiles.fileId, 'form.logoUrl': _this.data.form.logoFiles.fileUrl })
        }
      }
    })
  },
  uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (res) => {
          resolve(res)
        },
        (err) => {
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
  async getDetail () {
    try {
      const { ResultSet } = await getSupplierBrandInfo({ supplierBrandId: this.data.form.supplierBrandId })
      this.data.form = { ...this.data.form, ...ResultSet.userData.supplierBrandInformation }
      this.setData({ form: this.data.form })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ id }) {
    if (id) {
      wx.$pro.setNavigationBarTitle({ title: '编辑品牌' })
      this.setData({ 'form.supplierBrandId': id })
      this.getDetail()
    } else {
      wx.$pro.setNavigationBarTitle({ title: '添加品牌' })
    }
  }
})